﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Reporting.WebForms;
using System.Collections.Specialized;
using Library.Helpers;
using System.Collections;
using Core.IGateways;
using System.IO;

namespace Reports
{
    public abstract class BaseReport : IBaseReport
    {       
        public BaseReport()
        {     
        }

        protected abstract LocalReport BuildLocalReport(string reportPath, Hashtable parameters);

        protected virtual string deviceInfo
        {
            get
            {
                //The DeviceInfo settings should be changed based on the reportType
                //http://msdn2.microsoft.com/en-us/library/ms155397.aspx

                return
                "<DeviceInfo>" +
                "  <OutputFormat>PDF</OutputFormat>" +
                "  <PageWidth>22cm</PageWidth>" +
                "  <PageHeight>29.7cm</PageHeight>" +
                "  <MarginTop>0.0in</MarginTop>" +
                "  <MarginLeft>0.0in</MarginLeft>" +
                "  <MarginRight>0.0in</MarginRight>" +
                "  <MarginBottom>0.0in</MarginBottom>" +
                "</DeviceInfo>";
            }
        }

        public byte[] GetBytes(ReportFormatType formatType, string reportPath, Hashtable parameters)
        {
            LocalReport localReport = BuildLocalReport(reportPath, parameters);

            string reportType = formatType.ToString();
            string mimeType;
            string encoding;
            string fileNameExtension;

            Warning[] warnings;
            string[] streams;            

            return localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);
        }

        public Stream GetStream(ReportFormatType formatType, string reportPath, Hashtable parameters)
        {
            byte[] content = GetBytes(formatType, reportPath, parameters);
            return StreamHelper.CreateStreamFromByteArray(content);
        }

        public Stream GetPdf(string reportPath, Hashtable parameters)
        {
            return GetStream(ReportFormatType.Pdf, reportPath, parameters);
        }

        protected ReportDataSource CreateReportDataSource<T>(string sourceName, T sourceValue)
        {
            List<T> list = new List<T>();
            list.Add(sourceValue);
            return new ReportDataSource(sourceName, list);
        }        
    }
}
